package com.atguigu.juc.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description: CAS 思想自定义实现自旋锁
 * @author： yeswater
 * @create： 2024/5/30
 */

public class SpinLockDemo {
	
	AtomicReference<Thread> atomicReference = new AtomicReference<>();
	
	public void lock(){
		Thread thread = Thread.currentThread();
		System.out.println(Thread.currentThread().getName() + " come in");
		while (!atomicReference.compareAndSet(null, thread)){
			
		}
	}
	
	public void unlock(){
		Thread thread = Thread.currentThread();
		atomicReference.compareAndSet(thread, null);
		System.out.println(Thread.currentThread().getName() + " come out, unlock");
	}
	
	public static void main(String[] args) {
		
		SpinLockDemo spinLockDemo = new SpinLockDemo();
		new Thread(() -> {
			spinLockDemo.lock();
			try {
				TimeUnit.SECONDS.sleep(5);
			} catch (InterruptedException e) {
				throw new RuntimeException(e);
			}
			spinLockDemo.unlock();
		}, "t1").start();
		
		new Thread(() -> {
			spinLockDemo.lock();
			spinLockDemo.unlock();
		}, "t2").start();
	}
	
}
